package com.ynet.middleground.approve.service.impl;

import java.util.List;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Throwables;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.approve.bean.CreateProcessModelReq;
import com.ynet.middleground.approve.bean.ProcessModelReq;
import com.ynet.middleground.approve.bean.QueryModelReqPager;
import com.ynet.middleground.approve.dto.ProcessModelDTO;
import com.ynet.middleground.approve.model.ProcessModelerModel;
import com.ynet.middleground.approve.service.ProcessModelerService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @author liulx
 * @description 流程模型接口服务实现类
 * @date 2019-10-11 14:48
 */
@Api(value = "流程模型相关接口服务", tags = "流程模型相关接口服务（中台内管）")
@Produces({MediaType.APPLICATION_JSON + "; " + "charset=UTF-8", MediaType.TEXT_XML + "; " + "charset=UTF-8"})
@Path("models")
@Service(timeout = 6000, version = "0.0.1")
public class ProcessModelerServiceImpl implements ProcessModelerService {

    @Autowired
    private ProcessModelerModel processModelerModel;

    /**
     * 创建模型
     *
     * @param processModelReq 流程模型创建请求对象: {模型名称,key,描述}
     * @return 创建结果标志，返回模型id
     */
    @POST
    @ApiOperation(value = "创建模型（中台内管）", notes = "创建模型, 返回模型id，中台内管使用，渠道不需关心", produces = "application/json")
    @ApiImplicitParam(name = "requestObj", dataType = "CreateProcessModelReq", paramType = "body", required = true)
    @Override
    public ServiceResult<String> create(CreateProcessModelReq processModelReq) {
        ServiceResult<String> result = new ServiceResult();
        try {
            String modelId = processModelerModel.create(processModelReq);
            result.setResult(modelId);
        } catch (BusinessException be) {
            result.setError(be.getCode(), be.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "创建模型时服务异常: {}",
                Throwables.getStackTraceAsString(e));
            result.setError("ECAP0000", "服务异常，请联系系统管理员");
            return result;
        }
        return result;
    }

    /**
     * 发布模型
     *
     * @param processModelReq 流程模型发布请求对象: {模型ID}
     * @return 发布结果标志，以success 字段值标识 true/false
     */
    @PUT
    @ApiOperation(value = "发布模型（中台内管）", notes = "发布模型，中台内管使用，渠道不需要关心")
    @ApiImplicitParam(name = "requestObj", dataType = "ProcessModelReq", paramType = "body", required = true)
    @Override
    public ServiceResult publish(ProcessModelReq processModelReq) {
        ServiceResult<Object> result = new ServiceResult<>();
        try {
            processModelerModel.publish(processModelReq);
        } catch (BusinessException be) {
            result.setError(be.getCode(), be.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "部署模型服务异常: {}",
                Throwables.getStackTraceAsString(e));
            result.setError("00001", "模型发布失败，服务异常，请联系系统管理员。");
            return result;
        }
        return result;
    }

    /**
     * 分页查询流程模型列表
     *
     * @param queryModelReqPager 流程模型查询请求类: {模型名称, key}
     * @return 流程模型列表
     */
    @POST
    @Path("list")
    @ApiOperation(value = "分页查询流程模型列表（中台内管）", notes = "分页查询流程模型列表，中台内管使用，渠道不需要关心")
    @ApiImplicitParam(name = "requestObj", dataType = "QueryModelReqPager", paramType = "body", required = true)
    @Override
    public ServiceResult<List<ProcessModelDTO>> listModelByPage(QueryModelReqPager queryModelReqPager) {
        ServiceResult<List<ProcessModelDTO>> result = new ServiceResult<>();
        try {
            List<ProcessModelDTO> resultList = processModelerModel.listModelByPage(queryModelReqPager);
            result.setResult(resultList);
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "分页查询流程模型列表异常,case:{}",
                Throwables.getStackTraceAsString(e));
            result.setError("ECAP0000", "服务异常，请联系系统管理员");
            return result;
        }
        result.setPagerInfo(queryModelReqPager.getPagerInfo());
        return result;
    }

    /**
     * 删除模型
     *
     * @param processModelReq 删除模型请求对象: {模型ID}
     * @return 删除结果标志，以success 字段值标识 true/false
     */
    @DELETE
    @ApiOperation(value = "删除模型（中台内管）", notes = "根据模型ID删除模型，中台内管使用，渠道不需要关心")
    @ApiImplicitParam(name = "requestObj", dataType = "ProcessModelReq", paramType = "body", required = true)
    @Override
    public ServiceResult removeModelByModelId(ProcessModelReq processModelReq) {
        ServiceResult<Object> result = new ServiceResult<>();
        try {
            processModelerModel.removeModelByModelId(processModelReq);
        } catch (BusinessException be) {
            result.setError(be.getCode(), be.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "activiti根据流程模型ID删除模型失败,case:{}",
                Throwables.getStackTraceAsString(e));
            result.setError("ECAP0000", "服务异常，请联系系统管理员");
            return result;
        }
        return result;
    }
}
